import xml.parsers.expat
from go_node import *

class dump_log:
	"""
	Takes the GO xml file and creates a dump file for faster access
	The dump file is a text file with the following format
	1. GO_ID
	2. GO_NAME
	3. ISA1_GO_ID ISA2_GO_ID etc.
	4. GO_NAMESPACE
	5. GO_DESCRIPTION (would be left blank if the description is not provided)
	"""
	
	def __init__(self, dump_filename):
		self.working = False
		self.got_id = False
		self.got_name = False
		self.got_namespace = False
		self.got_definition = False
		self.got_isa = False
		self.node = None
		self.file = open(dump_filename, 'w')

	def start_tag(self, name, attrs):
		if name == "term":
			self.working = True
			self.node = None
			self.node = go_node()
		elif name == "id":
			self.got_id = True
		elif name == "name":
			self.got_name = True
		elif name == "namespace":
			self.got_namespace = True
		elif name == "defstr":
			self.got_definition = True
		elif name == "is_a":
			self.got_isa = True
			self.node.isa = []
		elif name == 'dbxref':
			self.working = False

	def end_tag(self, name):
		if name == "term":
			self.write_node()
			self.working = False
		elif name == "id":
			self.got_id = False
		elif name == "name":
			self.got_name = False
		elif name == "namespace":
			self.got_namespace = False
		elif name == "defstr":
			self.got_definition = False
		elif name == "is_a":
			self.got_isa = False
		elif name == 'dbxref':
			self.working = True

	def char_data(self, data):
		if self.working:
			if self.got_id:
				self.node['id'] = data[3:]
			elif self.got_name:
				self.node['name'] = data
			elif self.got_namespace:
				self.node['namespace'] = data
			elif self.got_definition:
				self.node['definition'] = data
			elif self.got_isa:
				self.node.isa.append(data[3:])
	
	def write_node(self):
		self.file.write(self.node['id']+'\n')
		self.file.write(self.node['name']+'\n')
		self.file.write(self.node['namespace']+'\n')
		if self.node['definition'] != "":
			self.file.write(self.node['definition']+'\n')
		else:
			self.file.write('\n')
		self.file.write(' '.join(self.node['isa']))
		self.file.write('\n')

	def dump_xmlfile(self, xml_filename):
		p = xml.parsers.expat.ParserCreate()
		
		p.StartElementHandler = self.start_tag
		p.EndElementHandler = self.end_tag
		p.CharacterDataHandler = self.char_data
		p.buffer_text = True
		
		p.ParseFile(open(xml_filename, 'r'))
		self.file.close()
